# -*- coding: utf-8 -*-  
"""  
@author   : Mengnf  
@github   : https://gitee.com/mengnf  
@software : PyCharm   
@file     : roles.py  
@create   : 2024-11-13 1:12  
"""

from rest_framework import serializers

from system.models import Roles, RolesPermissions
from system.serializers.permissions import PermissionsSerializer


class RolesSerializer(serializers.ModelSerializer):
    """
    角色管理序列化器
    """
    create_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    update_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = Roles
        fields = '__all__'
        extra_kwargs = {
            'permissions': {
                'read_only': True,
            },
        }


class RolesPartialSerializer(serializers.ModelSerializer):
    """
    用户局部更新序列化器(角色授权)
    """

    class Meta:
        model = Roles
        fields = ['id', 'permissions']

    def validate(self, attrs):
        permissions = attrs.get('permissions')
        for permission in permissions:
            if permission.pid and permission.pid not in permissions:
                raise serializers.ValidationError('缺失父节点权限')
        return attrs


class RolesPermissionsSerializer(serializers.ModelSerializer):
    """角色权限"""
    role = RolesSerializer()
    permissions = PermissionsSerializer()

    class Meta:
        model = RolesPermissions
        fields = '__all__'
